<?php namespace DH16\Tools;
/**
 * Author: 熊伟洋<chelious@foxmail.com>
 * WeChat: hello_McGrady
 * QQ:434493420
 * Date: 2017/4/19
 * Time: 08:42
 */

/**
 * 验证码类
 */
class Code{
	private $width;//画布宽
	private $height;//画布高
	private $bgcolor;//画布颜色
	private $img;//画布
	private $codeLen;//验证码数量
	private $size;//字体大小
	private $seed;//种子库

	public function __construct($width=null,$height=null,$bgcolor=null,$codeLen=null,$size=null,$seed=null)
	{
		$this->width = is_null($width) ? C('CODE_WID') : $width;
		$this->height = is_null($height) ?  C('CODE_HEI') : $height;
		$this->bgcolor = is_null($bgcolor) ? '#ffffff' : $bgcolor;
		$this->codeLen = is_null($codeLen) ?  C('CODE_LEN') : $codeLen;
		$this->size = is_null($size) ? C('CODE_SIZE') : $size;
		$this->seed = is_null($seed) ? 'zxcvbnmasdfghjklqwertyuiop1234567890' : $seed;
	}


	/**
	 * 总方法
	 */
	public function make(){
		//1.发送头部信息
		header('Content-type:image/png');
		//2.画布处理
		$this->createBg();
		//3.写字
		$this->write();
		//4.制造干扰
		$this->makeTrouble();
		//5.输出图像
		imagepng($this->img);
		//6.释放图像资源
		imagedestroy($this->img);
	}

	/**
	 * 画布处理
	 */
	private function createBg(){
		//1.创建画布
		$img = imagecreatetruecolor($this->width,$this->height);
		//2.取色 将十六进制的颜色转为十进制
//		$color = imagecolorallocate($img,251,0,0);
		$color = hexdec($this->bgcolor);
		//3.填充
		imagefill($img,0,0,$color);
		//4.将$img赋值给属性
		$this->img = $img;
	}

	/**
	 * 写字
	 */
	private function write(){
		$str = '';
		for ($i=0;$i<$this->codeLen;$i++){
			$x = ($this->width/$this->codeLen)*$i+10;
			$y = ($this->height+$this->size)/2;
			$color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
			$text = $this->seed[mt_rand(0,strlen($this->seed)-1)];
			$str .= $text;
			imagettftext($this->img,$this->size,mt_rand(-45,45),$x,$y,$color,'./DH16/Tools/simsun.ttc',$text);
		}
		$_SESSION['code'] = $str;
	}

	/**
	 * 制造干扰
	 */
	private function makeTrouble(){
		//画点
		for ($i=0;$i<1000;$i++){
			$color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
			imagesetpixel($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
		}

		//划线
		for ($i=0;$i<10;$i++){
			$color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
			imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
		}
	}
}
